import os
import xlwings as xw
from PIL import ImageGrab

def extract_images_with_xlwings():
    excel_path = r"F:\检查员分级筛选名单-20250415-0856.xlsx"
    output_folder = r"F:\checkerPicture"

    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    app = xw.App(visible=False)
    wb = app.books.open(excel_path)

    for sheet in wb.sheets:
        print(f"处理工作表: {sheet.name}")

        # 获取身份证号列（第5列）
        id_cards = sheet.range((2, 5), (sheet.cells.last_cell.row, 5)).value
        if not isinstance(id_cards, list):
            id_cards = [id_cards]

        # 获取所有图片对象
        all_pictures = sheet.pictures

        for i, id_card in enumerate(id_cards, start=2):
            if not id_card:
                continue

            # 检查第17列是否有图片
            for pic in all_pictures:
                # 获取图片左上角单元格位置
                top_left_cell = pic.top_left_cell

                # 检查是否在第17列且行号匹配
                if top_left_cell.column == 'Q' and top_left_cell.row == i:
                    try:
                        # 复制图片到剪贴板
                        pic.api.Copy()

                        # 从剪贴板获取图片并保存
                        img = ImageGrab.grabclipboard()
                        if img:
                            output_path = os.path.join(output_folder, f"{id_card}.png")
                            img.save(output_path)
                            print(f"已保存图片: {output_path}")
                    except Exception as e:
                        print(f"处理身份证号 {id_card} 时出错: {str(e)}")
                    break

    wb.close()
    app.quit()
    print("图片提取完成！")

extract_images_with_xlwings()
